<template>
  <a-layout>
    <!--右侧内容 数据渲染表格-->
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <div class="about">
<!--        <a-button type="primary" @click="showModal">-->
<!--          新增-->
<!--        </a-button>-->
        <a-table :columns="columns" :row-key="item => item.id" :data-source="categorys" :pagination="false"
                 :loading="isLoading" @change="handleTableChange">
          <template #bodyCell="{ column, text,record }">
            <template v-if="column.dataIndex === 'cover'">
              <img :src="text" alt="封面"/>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-space size="small">
                <a-button type="primary" @click="showModal(record)">
                  编辑
                </a-button>
                <a-popconfirm title="确认要删除此项数据吗?" ok-text="Yes" cancel-text="No" @confirm="confirm(record)" @cancel="cancel">
                <a-button danger>
                  删除
                </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-layout-content>
  </a-layout>
<!-- 增删弹窗-->
  <a-modal v-model:open="open" title="Title" :confirm-loading="confirmLoading" @ok="handOk">
    <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入作者"/>
      </a-form-item>
      <a-form-item label="父分类" name="parent">
        <a-select ref="select"  v-model:value="formState.parent">
          <a-select-option :value="0">无</a-select-option>
          <a-select-option v-for="item in categorys" :key="item.id" :value="+item.id" :disabled="formState.id == item.id">{{item.name}}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="排序" name="category2Id">
        <a-input v-model:value="formState.sort" placeholder="请输入排序"/>
      </a-form-item>
    </a-form>
  </a-modal>
<!--  错误提醒弹窗-->
    <context-holder />
</template>
<script setup lang="ts">
import { onMounted, ref, reactive,computed,toRaw,UnwrapRef} from 'vue';
import {arrayToTree}  from "@/utils/tools";
import axios from 'axios';
import { message } from 'ant-design-vue';
// 表格结构
const columns = [
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '父分类',
    dataIndex: 'parent'
  },
  {
    title: '顺序',
    dataIndex: 'sort'
  },
  {
    title: 'Action',
    dataIndex: 'action',
  }

];
// 表格数据
let categorys: any[] = [];
//分页信息
const pagination = ref({
  pageSize: 100,
  total: 0,
  current: 1
})

// 数据加载状态
const isLoading = ref(true)
// 页面加载时，请求数据
onMounted(async () => {
  render()
})
// 渲染表格数据
function render(){
   axios.get('/category/selectByPage',{
    params:{
      page:pagination.value.current,
      size:pagination.value.pageSize
    }
  }).then(res => {
     console.log(res.data.data.list.length)
    if(res.data.data.list.length==0){
      pagination.value.current = pagination.value.current-1;
      render()
    }
    // 加载完成
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    categorys = arrayToTree(res.data.data.list);
  })
}
//  表格分页
const handleTableChange = (pag: any) => {
  console.log('handleTableChange', pagination)
  pagination.value.current = pag.current;
  render()
}
const modalText = ref<string>('Content of the modal');
const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
// 表单
const labelCol = {style: {width: '150px'}};
const wrapperCol = {span: 14};
// 编辑数据显示弹窗
const showModal = (record: any) => {
  open.value = true;
  //  弹窗内容
  // modalText.value = JSON.stringify(record);
  //  弹窗内容
  formState.id = record.id;
  formState.name = record.name;
  formState.parent = record.parent;
  formState.sort = record.sort;
};

// 表单类型
// 表单类型
interface categoryFormState {
  id: number;
  name: string;
  parent: number;
  sort: number;
}

// 表单数据
const formState = reactive<categoryFormState>({
  id: 0,
  name: '',
  parent: 0,
  sort: 0
})

const [messageApi, contextHolder] = message.useMessage();
//增加删除确认
function  handOk(){
  modalText.value = 'The modal will be closed after two seconds';
  confirmLoading.value = true;
  axios.post('/category/saveOrUpdate', formState).then((res: { data: { code: number; }; }) => {
    if (res.data.code === 200) {
      //  关闭弹窗
      open.value = false;
      confirmLoading.value = false;
      //  重新请求数据
      render();
      messageApi.info("操作成功");
    }
  }).catch((error: { response: { status: any; data: any; headers: any; }; request: any; message: any; }) => {
    if (error.response) {
      //  关闭弹窗,提示错误信息
      open.value = false;
      confirmLoading.value = false;
      console.log(error.response.data);
      messageApi.info(error.response.data.errors[0].defaultMessage);
    }
    // else if (error.request) {
    //   // 请求已发送，但没有收到响应
    //   console.error('Request:', error.request);
    // } else {
    //   // 在设置请求时发生错误
    //   console.error('Error Message:', error.message);
    // }
})
}
//删除确认和取消弹窗
const confirm = (record:any) => {
  console.log(record.id);
  axios.post('/category/deleteById/'+record.id).then(() => {
    // 加载完成
    isLoading.value = false;
    message.success('删除成功');
    // mySafeAsyncFunction()
    render()
  })
};
//取消删除
const cancel = (record: any) => {
  console.log(record.id);
  message.error('取消删除');
};


</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
img {
  width: 50px;
  height: 50px;
}
</style>